// Application/Features/Roles/Queries/GetRoleDetail/GetRoleDetailQueryHandler.cs
using MediatR;
using UniversalAdmin.Application.Common;
using UniversalAdmin.Application.DTOs;
using UniversalAdmin.Domain.Interfaces;

namespace UniversalAdmin.Application.Features.Roles.Queries.GetRoleDetail;

public class GetRoleDetailQueryHandler : IRequestHandler<GetRoleDetailQuery, ApiResult<RoleDto>>
{
  private readonly IUnitOfWork _uow;

  public GetRoleDetailQueryHandler(IUnitOfWork uow) => _uow = uow;

  public async Task<ApiResult<RoleDto>> Handle(GetRoleDetailQuery request, CancellationToken ct)
  {
    var role = await _uow.RoleRepository.GetRoleWithMenusAsync(request.Id);
    if (role == null) return ApiResult<RoleDto>.Failure(404, "角色不存在");

    return ApiResult<RoleDto>.Success(new RoleDto
    {
      Id = role.Id,
      Name = role.Name,
      Description = role.Description,
      IsActive = role.IsActive,
      CreatedAt = role.CreatedAt,
      UpdatedAt = role.UpdatedAt,
      Menus = role.RoleMenus.Select(rm => new MenuDto
      {
        Id = rm.Menu!.Id,
        Name = rm.Menu.Name,
        Path = rm.Menu.Path,
        Icon = rm.Menu.Icon,
        ParentId = rm.Menu.ParentId,
        Sort = rm.Menu.Sort,
        IsActive = rm.Menu.IsActive
      }).ToList()
    });
  }
}